<!-- 起草合同 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" showBack> </pageHeaderNew>
    </template>
    <div class="template-steps">
      <a-steps changeable :current="current" @change="setCurrent">
        <a-step>合同信息</a-step>
        <a-step>合同编辑</a-step>
        <a-step>合同预览</a-step>
        <a-step>合同签署</a-step>
      </a-steps>
    </div>
    <!-- 基础信息 -->
    <div v-show="current === 1">
      <ContractBaseInfo ref="baseInfoRef" v-model:data="templateData.data" />
    </div>

    <!-- 合同文本 -->
    <div v-show="current === 2">
      <ContractDesign ref="designRef" v-model:data="templateData.data" />
    </div>
    <!-- 合同预览 -->
    <div v-show="current === 3">
      <!-- <AssessmentIndex v-model:data="templateData" /> -->
      <ContractPreview v-model:data="templateData.data" />
    </div>
    <!-- 合同签署 -->
    <div v-show="current === 4">
      <ContractSign ref="signRef" v-model:data="templateData.data" />
    </div>
    <footer>
      <a-space>
        <a-button
          class="btn"
          type="secondary"
          :disabled="current <= 1"
          @click="onPrev"
        >
          <IconLeft />
          上一步
        </a-button>
        <a-button
          class="btn"
          type="primary"
          v-show="current !== 4"
          :disabled="current >= 4"
          @click="onNext"
        >
          下一步
          <IconRight />
        </a-button>
        <a-button
          class="btn"
          type="outline"
          v-show="current === 4"
          @click="save"
        >
          确认并保存
        </a-button>
        <!-- <a-button
          class="btn"
          type="primary"
          v-show="current === 4"
          @click="send"
        >
          确认发起
        </a-button> -->
        <a-button class="btn" type="secondary" @click="router.back()">
          取消
        </a-button>
      </a-space>
    </footer>
  </ContentCard>
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import dayjs from 'dayjs';
import { changeControlData } from '@/utils/control';
import { PerformanceAppraisal } from '@/apis/management/performance/baseSetting/template/type';
import { GetHumanRosterDetail } from '@/apis/management/human/humanChange/leave';
import {
  SwitchDraftWaitSignedContract,
  DraftWaitSignedContractSave,
  GetGenerateContractNum,
  DraftWaitSignedContractSavePut,
  GetUserContractByStatusDetail,
  ChangeWaitSignedContractState,
  DraftWaitSignedContractSavePutStatus
} from '@/apis/management/contract/contractManagement/waitSigned';
import { GetBusinessModalData } from '@/apis/controltotal';
import ContractBaseInfo from './ContractBaseInfo.vue';
import ContractDesign from './ContractDesign.vue';
import ContractSign from './ContractSign.vue';
import ContractPreview from './ContractPreview.vue';
import { Message } from '@arco-design/web-vue';
import { useVModel } from '@vueuse/core';

const props = withDefaults(
  defineProps<{
    data?: PerformanceAppraisal;
  }>(),
  {}
);
// const emit = defineEmits(['update:visible', 'update:data', 'handleOk', 'save']);
const route = useRoute();
const router = useRouter();
let userIds: any;
try {
  userIds = JSON.parse(route.query.jsonStr + '').userIds;
} catch (err) {
  //
}
const title = '起草合同';

let baseInfoRef = ref(); // 基础信息ref
let designRef = ref(); // 合同编辑ref
let signRef = ref(); // 合同签署ref
let pageHeaderSettingRef = ref();
let fileSettingRef = ref();
const templateData = reactive({
  data: {
    userData: [],
    baseInfoData: {
      companyId: undefined, // 企业签署方id
      templateTypeId: undefined, // 合同的typeid
      templateId: undefined, // 合同id
      templateName: '', // 合同名称
      templateInfo: {}, // 合同模板详情信息
      // 合同模板其他信息
      // templateInfo: {
      //   enterpriseName: '', // 企业名称
      //   logo: '', // 企业logo
      //   style: 1 // 模板页眉样式
      // },
      annexData: [], // 附件信息
      annexName: [], // 附件名称
      remark: ''
    },
    designData: [],
    preViewData: [], // 预览数据
    signData: []
  }
});

// 获取起草合同详情
// const getData = async () => {
//   try {
//     const res = await GetUserContractByStatusDetail({
//       id: 93
//     });

//     templateData.data.baseInfoData.companyId = res.companyId;
//     templateData.data.baseInfoData.id = res.id;
//     templateData.data.baseInfoData.templateId = res.children[0].id;
//     templateData.data.baseInfoData.templateTypeId = res.children[0].typeId;
//     templateData.data.baseInfoData.templateName = res.children[0].name;
//     templateData.data.baseInfoData.templateInfo = res.children[0];
//     for (let i = 1; i < res.children.length; i++) {
//       templateData.data.baseInfoData.annexData.push(res.children[i]);
//     }

//     console.log(templateData.data);
//   } catch (error: unknown) {
//     console.log(error);
//   }
// };
// getData();
// 获取人员信息
const getUserData = async () => {
  try {
    for (let id of userIds) {
      const res = await GetHumanRosterDetail({
        id
      });
      templateData.data.userData.push(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
getUserData();

let controlList = ref([]); // 储存空间数据
const getControlData = async () => {
  const { funcCtlInfos } = (await GetBusinessModalData({
    funcCode: 'SER_FUNC751D0BFF5DF442209D437EE9A581693E'
  })) as any;
  controlList.value = changeControlData(funcCtlInfos, 'ctlDetail');
};
getControlData();
const current = ref(1);
const reset = () => {
  current.value = 1;
};
const onPrev = () => {
  current.value = Math.max(1, current.value - 1);
};
const onNext = async () => {
  // const check = await baseInfoRef.value.validate();
  // if (check) return;
  current.value = Math.min(4, current.value + 1);
  if (current.value > 1) {
    if (await checkValidate(baseInfoRef.value.validate)) {
      Message.error('请先填写必填信息！');
      current.value = 1;
      return;
    }
  }
  if (current.value === 3) {
    const res = await designRef.value.tabs.data;

    // 过滤出非空的元素
    const nonEmptyRes = cloneDeep(res.filter((i) => i));
    for (let i of nonEmptyRes) {
      for (let i2 in i) {
        i[i2].text = await switchCodes(i[i2]);
      }
    }
    templateData.data.preViewData = nonEmptyRes;
  }
};
const setCurrent = async (n: number) => {
  current.value = n;
  if (current.value > 1) {
    if (await checkValidate(baseInfoRef.value.validate)) {
      current.value = 1;
      Message.error('请先填写必填信息！');
      return;
    }
  } else if (current.value === 3) {
    const res = await designRef.value.tabs.data;

    // 过滤出非空的元素
    const nonEmptyRes = cloneDeep(res.filter((i) => i));
    for (let i of nonEmptyRes) {
      for (let i2 in i) {
        i[i2].text = await switchCodes(i[i2]);
      }
    }
    templateData.data.preViewData = nonEmptyRes;
  }
};

const checkValidate = async (validate: any) => {
  // console.log('=================================await validate()===');
  // console.log(await validate());
  // console.log('====================================');
  if (await validate()) return true;
  else return false;
};

// 将控件名字转换成控件code
const switchCodes = async (data: any) => {
  try {
    controlList.value.forEach((item: any) => {
      let regexp = new RegExp(`#${item.ctlCnName}#`, 'g');
      // currTemplate.value = currTemplate.value.replace(regexp, `#${item.cnName}#`);
      data.text = data.text.replace(regexp, `#${item.ctlCode}#`);
    });
    if (data.style !== 3) {
      const header = `<h3 style="text-align: ${
        data.style === 2 ? 'center' : 'left'
      }"><img src="${
        data.logo
      }" style="width: 40px; height: 40px; border-radius: 50%;"/> ${
        data.enterpriseName
      }</h3><br/>`;

      data.text = header + data.text;
    }
    const res = await SwitchDraftWaitSignedContract({
      id: data.userInfo.id,
      text: data.text,
      codes: data.codes
    });
    return res;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 获取合同预警时间
const countRemindDate = (date: string, num: number) => {
  const tempDay = dayjs(date);
  const result = tempDay.subtract(num, 'day');
  return result.format('YYYY-MM-DD');
};

// 获取合同编号
const getContractNum = async (id: number, userId: number) => {
  try {
    const res = await GetGenerateContractNum({
      id,
      userId
    });
    return res;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 判断一个对象属性是否为空
function hasEmptyPropertyValue(obj) {
  for (let key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      if (key !== 'contractNum' && key !== 'remindTime') {
        if (!obj[key]) {
          return true;
        }
      }
    }
  }
  return false;
}

// 确认并保存
const save = async () => {
  try {
    if (current.value === 4) {
      for (let i of templateData.data.signData) {
        if (hasEmptyPropertyValue(i)) {
          Message.error('请先填写必填信息');
          return;
        }
      }
    }

    templateData.data.designData = cloneDeep(
      designRef.value.tabs.data.filter((i) => i)
    );
    console.log('====================================templateData');
    console.log(templateData.data);
    console.log(Object.values(templateData.data.preViewData[0]));
    console.log('====================================');
    let contractList = [];
    for (let i = 0; i < templateData.data.userData.length; i++) {
      let children = [];

      Object.values(templateData.data.designData[i]).forEach((el: any) => {
        children.push(el);
      });
      templateData.data.signData[i].contractNum = await getContractNum(
        templateData.data.baseInfoData.templateTypeId,
        templateData.data.userData[i].id
      );
      templateData.data.signData[i].remindTime = countRemindDate(
        templateData.data.signData[i].signature,
        templateData.data.signData[i].remind
      );
      contractList.push({
        userId: templateData.data.userData[i].id,
        companyId: templateData.data.baseInfoData.companyId,
        typeId: templateData.data.baseInfoData.templateTypeId,
        templateId: templateData.data.baseInfoData.templateId,
        remark: templateData.data.baseInfoData.remark,
        children,
        contractName: templateData.data.signData[i].contractName,
        contractNum: templateData.data.signData[i].contractNum,
        way: templateData.data.signData[i].way,
        overTime: templateData.data.signData[i].overTime,
        expire: templateData.data.signData[i].expire,
        signature: templateData.data.signData[i].signature,
        remindTime: templateData.data.signData[i].remindTime,
        remind: templateData.data.signData[i].remind,
        status: 1, // 起草合同保存默认传1
        isChang: 2
      });
    }
    console.log(contractList);

    await DraftWaitSignedContractSave({
      contractList
    });
    router.back();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 确认发起
const send = async () => {
  try {
    try {
      if (current.value === 4) {
        for (let i of templateData.data.signData) {
          if (hasEmptyPropertyValue(i)) {
            Message.error('请先填写必填信息');
            return;
          }
        }
      }

      templateData.data.designData = cloneDeep(
        designRef.value.tabs.data.filter((i) => i)
      );
      console.log('====================================templateData');
      console.log(templateData.data);
      console.log(Object.values(templateData.data.preViewData[0]));
      console.log('====================================');
      let contractList = [];
      let ids: number[] = [];
      for (let i = 0; i < templateData.data.userData.length; i++) {
        let children = [];
        ids.push(templateData.data.userData[i].id);
        Object.values(templateData.data.designData[i]).forEach((el: any) => {
          children.push(el);
        });
        templateData.data.signData[i].contractNum = await getContractNum(
          templateData.data.baseInfoData.templateTypeId,
          templateData.data.userData[i].id
        );
        templateData.data.signData[i].remindTime = countRemindDate(
          templateData.data.signData[i].signature,
          templateData.data.signData[i].remind
        );
        contractList.push({
          userId: templateData.data.userData[i].id,
          companyId: templateData.data.baseInfoData.companyId,
          typeId: templateData.data.baseInfoData.templateTypeId,
          templateId: templateData.data.baseInfoData.templateId,
          remark: templateData.data.baseInfoData.remark,
          children,
          contractName: templateData.data.signData[i].contractName,
          contractNum: templateData.data.signData[i].contractNum,
          way: templateData.data.signData[i].way,
          overTime: templateData.data.signData[i].overTime,
          expire: templateData.data.signData[i].expire,
          signature: templateData.data.signData[i].signature,
          remindTime: templateData.data.signData[i].remindTime,
          remind: templateData.data.signData[i].remind,
          status: 1 // 起草合同发起暂时传8，应该是传4的
        });
      }
      console.log(contractList);

      await DraftWaitSignedContractSave({
        contractList
      });

      await DraftWaitSignedContractSavePutStatus({
        ids,
        status: 4
      });
      router.back();
    } catch (error: unknown) {
      console.log(error);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
.template-steps {
  padding: 0 160px;
  margin-bottom: 60px;
}
footer {
  height: 100px;
  padding-top: 15px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
</style>
